<?php

namespace App\Http\Controllers;

use App\Http\Requests\BuyVipRequest;

use App\Models\User;
use App\Models\UserDcoinsLog;
use App\Models\UserPointsLog;
use App\Models\UserVipInfo;
use App\Models\UserVipOpeLog;
use App\Models\VipBaseInfo;
use App\Models\UserVipFreeOpeCountLog;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use App\Models\YzPayment;
use Auth;
use App\Pay\Youzan;


class VipController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        $vipInfos = VipBaseInfo::get();
        $user = Auth::user();
        if ($user->isVip())
        {
            throw new \Exception('已经是会员，不能再次购买');
        }
        //创建有赞支付二维码
        $price = 200;
        if($vipInfos)
        {
            $price = $vipInfos[0]->price;
        }
        $qr_img = null;
        $qr_id = 0;
        $qr = Youzan::createQRCode($price);
        $payment_type = YzPayment::TYPE_VIP;
        if(!empty($qr))
        {
            $qr_img = $qr['qr_code'];
            $qr_id = $qr['qr_id'];

            $yz_payment_arr = ['user_id' => $user->id,'qr_id' => $qr['qr_id'],
                'qr_price' => $price, 'status' => YzPayment::TRADE_NOT_PAY,
                'type' => YzPayment::TYPE_VIP, 'vip_id' => 1,
                'created_at' => Carbon::now(),'updated_at' => Carbon::now()];

            $payment_id = DB::table('yz_payments')->insertGetId($yz_payment_arr);

        }

        return view('vip.index',compact('vipInfos', 'user', 'price', 'qr_img', 'qr_id', 'payment_id','payment_type'));
    }

    public function buy(BuyVipRequest $request)
    {
        /** @var User $user */
        $user = \Auth::user();

        if ($user->isVip())
        {
            throw new \Exception('已经是会员，不能再次购买');
        }
        /** @var VipBaseInfo $vipBaseInfo */
        $vipBaseInfo = VipBaseInfo::find($request->id);

        $expireDate = $vipBaseInfo->getExpireDate(Carbon::now());

        $userVipInfo = [
            'vip_base_info_id' => $request->id,
            'vip_name' => $vipBaseInfo->name,
            'privilege_str' => $vipBaseInfo->privilege_str,
            'homework_help_discount' => $vipBaseInfo->homework_help_discount,
            'algorithm_sources_discount' => $vipBaseInfo->algorithm_sources_discount,
            'resource_discount' => $vipBaseInfo->resource_discount,
            'is_exempt_ads' => $vipBaseInfo->is_exempt_ads,
            'start_date' => date('Y-m-d H:i:s', time()),
            'expire_date' => $expireDate,
        ];

        $points = UserPointsLog::getLatestUPLog($user->id);
        $Dconin = UserDcoinsLog::getLatestUDcoinLog($user->id);
        $userVipFreeOpeCountLog = UserVipFreeOpeCountLog::getLatestLog($user->id);
        $newUserVipFreeOpeCountLog = new UserVipFreeOpeCountLog();
        $userVipOpeLog = new UserVipOpeLog();

        $userVipOpeLog->user_id = $user->id;
        $userVipOpeLog->vip_id = $vipBaseInfo->id;
        $userVipOpeLog->vip_info = $vipBaseInfo;
        $userVipOpeLog->user_vip_info = $userVipInfo;
        $userVipOpeLog->remark = '开通vip';

        $newUserVipFreeOpeCountLog->user_id = $user->id;
        $newUserVipFreeOpeCountLog->ope = UserVipFreeOpeCountLog::ADD_OPE;
        $newUserVipFreeOpeCountLog->free_home_help_ope_count = $vipBaseInfo->free_homework_help_count;
        $newUserVipFreeOpeCountLog->free_home_help_remain_count = ($userVipFreeOpeCountLog->free_home_help_remain_count ?? 0) + $vipBaseInfo->free_homework_help_count;
        $newUserVipFreeOpeCountLog->free_resource_ope_count = $vipBaseInfo->free_resource_point_count;
        $newUserVipFreeOpeCountLog->free_resource_remain_count = ($userVipFreeOpeCountLog->free_resource_remain_count ?? 0) + $vipBaseInfo->free_resource_point_count;
        $newUserVipFreeOpeCountLog->free_algorithm_sources_ope_count = $vipBaseInfo->free_algorithm_sources_count;
        $newUserVipFreeOpeCountLog->free_algorithm_sources_remain_count = ($userVipFreeOpeCountLog->free_algorithm_sources_remain_count ?? 0) + $vipBaseInfo->free_algorithm_sources_count;
        $newUserVipFreeOpeCountLog->remark = '开通vip：' . $vipBaseInfo->privilege_str;

        DB::transaction(function () use ($user, $userVipInfo, $newUserVipFreeOpeCountLog, $userVipOpeLog, $vipBaseInfo) {
            $user->vipInfo()->updateOrCreate(['user_id' => $user->id], $userVipInfo);
            $newUserVipFreeOpeCountLog->save();
            $userVipOpeLog->save();

            if ($vipBaseInfo->resource_point > 0) {
                $newPoints = new UserPointsLog();
                $newPoints->user_id = $user->id;
                $newPoints->type = 1; //增加
                $newPoints->points = $vipBaseInfo->resource_point;
                $newPoints->remain_points = ($points->remain_points ?? 0) + $vipBaseInfo->resource_point;
                $newPoints->reason_type = UserPointsLog::REASON_TYPE_VIP_ADD;
                $newPoints->remark = '开通vip：' . $vipBaseInfo->privilege_str;
                $newPoints->save();
            }

            if ($vipBaseInfo->algorithm_sources_icon > 0) {
                $newDconin = new UserDcoinsLog();
                $newDconin->user_id = $user->id;
                $newDconin->type = 1; //增加
                $newDconin->dcoins = $vipBaseInfo->algorithm_sources_icon;
                $newDconin->remain_dcoins = ($Dconin->remain_dcoins ?? 0) + $vipBaseInfo->algorithm_sources_icon;
                $newDconin->reason_type = UserDcoinsLog::REASON_TYPE_VIP_ADD;
                $newDconin->remark = '开通vip：' . $vipBaseInfo->privilege_str;
                $newDconin->save();
            }
        });

        return response(['created' => true], 201);
    }

    public function renew(BuyVipRequest $request)
    {
        /** @var User $user */
        $user = \Auth::user();
        /** @var UserVipInfo $userVipInfo */
        $userVipInfo = $user->vipInfo()->first();
        if (empty($userVipInfo) || $userVipInfo->vip_base_info_id != $request->id) {
            throw new \Exception('该会员你还未购买,请购买后续费!');
        }
        /** @var VipBaseInfo $vipBaseInfo */
        $vipBaseInfo = VipBaseInfo::find($request->id);

        $expireDate = $vipBaseInfo->getExpireDate(Carbon::createFromTimeString($userVipInfo->expire_date));

        $userVipInfo->expire_date = $expireDate;

        $points = UserPointsLog::getLatestUPLog($user->id);
        $newPoints = new UserPointsLog();
        $Dconin = UserDcoinsLog::getLatestUDcoinLog($user->id);
        $newDconin = new UserDcoinsLog();
        $userVipFreeOpeCountLog = UserVipFreeOpeCountLog::getLatestLog($user->id);
        $newUserVipFreeOpeCountLog = new UserVipFreeOpeCountLog();
        $userVipOpeLog = new UserVipOpeLog();

        $userVipOpeLog->user_id = $user->id;
        $userVipOpeLog->vip_id = $vipBaseInfo->id;
        $userVipOpeLog->vip_info = $vipBaseInfo;
        $userVipOpeLog->user_vip_info = $userVipInfo;
        $userVipOpeLog->remark = '续费vip';

        if ($vipBaseInfo->resource_point > 0) {
            $newPoints->user_id = $user->id;
            $newPoints->type = 1; //增加
            $newPoints->points = $vipBaseInfo->resource_point;
            $newPoints->remain_points = ($points->remain_points ?? 0) + $vipBaseInfo->resource_point;
            $newPoints->reason_type = UserPointsLog::REASON_TYPE_VIP_ADD;
            $newPoints->remark = '续费vip：' . $vipBaseInfo->privilege_str;
        }

        if ($vipBaseInfo->algorithm_sources_icon > 0) {
            $newDconin->user_id = $user->id;
            $newDconin->type = 1; //增加
            $newDconin->dcoins = $vipBaseInfo->algorithm_sources_icon;
            $newDconin->remain_dcoins = ($Dconin->remain_dcoins ?? 0) + $vipBaseInfo->algorithm_sources_icon;
            $newDconin->reason_type = UserDcoinsLog::REASON_TYPE_VIP_ADD;
            $newDconin->remark = '续费vip：' . $vipBaseInfo->privilege_str;
        }

        $newUserVipFreeOpeCountLog->user_id = $user->id;
        $newUserVipFreeOpeCountLog->ope = UserVipFreeOpeCountLog::ADD_OPE;
        $newUserVipFreeOpeCountLog->free_home_help_ope_count = $vipBaseInfo->free_homework_help_count;
        $newUserVipFreeOpeCountLog->remain_count = ($userVipFreeOpeCountLog->free_home_help_remain_count ?? 0) + $vipBaseInfo->free_homework_help_count;
        $newUserVipFreeOpeCountLog->free_resource_ope_count = $vipBaseInfo->free_resource_point_count;
        $newUserVipFreeOpeCountLog->free_resource_remain_count = ($userVipFreeOpeCountLog->free_resource_remain_count ?? 0) + $vipBaseInfo->free_resource_point_count;
        $newUserVipFreeOpeCountLog->free_algorithm_sources_ope_count = $vipBaseInfo->free_algorithm_sources_count;
        $newUserVipFreeOpeCountLog->free_algorithm_sources_remain_count = ($userVipFreeOpeCountLog->free_algorithm_sources_remain_count ?? 0) + $vipBaseInfo->free_algorithm_sources_count;
        $newUserVipFreeOpeCountLog->remark = '续费vip：' . $vipBaseInfo->privilege_str;

        DB::transaction(function () use ($userVipInfo, $newPoints, $newDconin, $newUserVipFreeOpeCountLog, $userVipOpeLog) {
            $userVipInfo->save();
            $newPoints->save();
            $newDconin->save();
            $newUserVipFreeOpeCountLog->save();
            $userVipOpeLog->save();
        });
    }

}
